import 'package:dio/dio.dart';

//自定义 http 异常
class CnHttpException implements Exception {
  final int code;
  final String msg;

  CnHttpException(
      {this.code = 500, this.msg = 'Network busy, please try again later!'});

  String toString() {
    return 'HttpError [$code]: $msg';
  }

  factory CnHttpException.create(DioError error) {
    //dio异常
    switch (error.type) {
      case DioErrorType.cancel:
        return CnHttpException(code: -1, msg: 'Request cancellation');
        break;
      case DioErrorType.connectTimeout:
        return CnHttpException(code: -1, msg: 'timed out');
        break;
      case DioErrorType.sendTimeout:
        return CnHttpException(code: -1, msg: 'timed out');
        break;
      case DioErrorType.receiveTimeout:
        return CnHttpException(code: -1, msg: 'timed out');
        break;
      case DioErrorType.response:
        {
          int? stateCode = error.response?.statusCode;
          return CnHttpException(
            code: stateCode!,
            msg: error.response!.statusMessage!,
          );
        }
        break;
      default:
        return CnHttpException(
          code: 500,
          msg: error.message,
        );
        break;
    }
  }
}
